package com.silence.whereeat.dao;

import com.silence.whereeat.model.UserFood;
import com.silence.whereeat.service.UserFoodService;
import com.silence.whereeat.utils.DBUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 食品评论
 * Created by 伟阳 on 2015/9/14.
 */
public class UserFoodDao implements UserFoodService {

    private DBUtils dbUtils;

    public UserFoodDao() {
        dbUtils = new DBUtils();
    }

    public int commentFood(UserFood userFood) {
        String sql = "INSERT INTO user_food VALUES (?,?,?,?);";
        List<Object> list = new ArrayList<Object>();
        list.add(userFood.getUser_id());
        list.add(userFood.getFood_id());
        list.add(userFood.getStar());
        list.add(userFood.getComment());
        int result = -1;
        try {
            result = dbUtils.updateByPreParedStatement(sql, list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public double getAverageStar(int foodId) {
        String sql = "SELECT AVG(star) AS avg FROM user_food WHERE food_id=?;";
        List<Object> list = new ArrayList<Object>();
        list.add(foodId);
        double result = -1;
        try {
            result = Double.parseDouble(dbUtils.querySingleResult(sql, list).get("avg").toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public List<UserFood> getComments(int passage) {
        String sql = "SELECT * " +
                "FROM user_food " +
                "LIMIT ?,?;";
        List<Object> list = new ArrayList<Object>();
        list.add(passage * 10);
        list.add(passage * 10 + 9);
        List<UserFood> comments = null;
        try {
            comments = dbUtils.queryResultSet(sql, list, UserFood.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return comments;
    }

    public void close() {
        dbUtils.close();
    }
}
